<template>
  <div class="dialog">
    <div class="header">
      文件库
      <span class="x" @click="emit('close')">X</span>
    </div>
    <div class="content">
      <div v-if="!!Object.keys(files).length">
        <div class="table-header">
          <div class="name">
            文件名
          </div>
          <div class="save-time">
            修改时间
          </div>
        </div>
        <div v-for="(file, id, index) in showFiles" :key="id" class="table-row">
          <div class="name" @click="openFile(id)">
            <i class="icon-24gl-fileText iconfont"/>
            <div class="text">
              {{ file.name }}
            </div>
          </div>
          <div class="save-time">
            {{ formatTimestamp(file.saveTime) }}
          </div>
          <div class="more-option">
            <el-dropdown trigger="click" ref="dropdownRefs">
              <i class="iconfont icon-gengduo"/>
              <template #dropdown>
                <div class="dropdown">
                  <div v-for="menu in dropdownMenus" :key="menu.id" @click="menu.callback(id, dropdownRefs[index])" :class="`row ${menu.id}`">
                    <i :class="`iconfont ${menu.icon}`"/>
                    <div class="text">
                      {{ menu.name }}
                    </div>
                  </div>
                </div>
              </template>
            </el-dropdown>
          </div>
        </div>
        <el-pagination :page-size="10" v-model:current-page="currentPage" layout="prev, pager, next, jumper" :total="keys.length" class="pagination"/>
      </div>
      <div style="text-align: center; padding: 10px 0;" v-else>
        暂无数据
      </div>
    </div>
  </div>
  <el-dialog v-model="centerDialogVisible" width="50%" center style="border-radius: 12px;">
    <div class="dialog">
      <div class="header">
        重命名
        <span class="x" @click="centerDialogVisible = false;">X</span>
      </div>
      <div class="content">
        <el-input v-model="titleInput" placeholder="请输入文件名" style="padding: 20px;"/>
        <div class="buttons">
          <div class="confirm button" @click="renameConfirm">
            确定
          </div>
          <div class="cancel button" @click="centerDialogVisible = false;">
            取消
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import {computed, ref} from 'vue'
import {storeToRefs} from 'pinia'
import {useStore} from '../store/index.js'
import HTMLtoDOCX from 'html-to-docx'
import {saveAs} from 'file-saver'

const store = useStore()
const { openFileStatus } = storeToRefs(store)
const emit = defineEmits(['close'])
const files = ref(JSON.parse((()=>{
  let docs = localStorage.getItem('docs');
  if (!docs) {
    return '{}'
  }else{
    return docs
  }
})()))
const keys = computed(()=>{return Object.keys(files.value).reverse()})
const reversedFiles = computed(()=>{
  const tmp = {}
  for (let i = 0; i < keys.value.length; i++) {
    tmp[keys.value[i]] = files.value[keys.value[i]]
  }
  return tmp
})
const currentPage = ref(1)
const showFiles = computed(()=>{
  const tmp = {}
  for(let i = (currentPage.value - 1) * 10; i < Math.min(currentPage.value * 10, keys.value.length); i++){
    tmp[keys.value[i]] = reversedFiles.value[keys.value[i]]
  }
  return tmp
})
const dropdownRefs = ref(null)
const dropdownMenus = ref([
  {
    id: 'open',
    name: '打开',
    icon: 'icon-24gl-fileText',
    callback: openFile
  },
  {
    id: 'download',
    name: '下载Word文档',
    icon: 'icon-xiazai',
    callback: downloadFile
  },
  {
    id: 'rename',
    name: '重命名',
    icon: 'icon-zhongmingming',
    callback: renameFile
  },
  {
    id: 'delete',
    name: '删除',
    icon: 'icon-shanchu',
    callback: deleteFile
  }
])
const centerDialogVisible = ref(false)
const titleInput = ref('')
function formatTimestamp(timestamp) {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${year}年${month}月${day}日 ${hours}:${minutes}`;
}
function openFile(id, dropRef){
  openFileStatus.value.status = true
  openFileStatus.value.id = id
  openFileStatus.value = {
    status: true,
    id: id,
    fileHtml: files.value[id].content,
    fileName: files.value[id].name
  }
  dropRef.handleClose()
  emit('close')
}
async function downloadFile(id, dropRef) {
  const fileBuffer = await HTMLtoDOCX(files.value[id].content)
  const fileName = files.value[id].name
  saveAs(fileBuffer, `${fileName ? fileName : '无标题'}.docx`);
  dropRef.handleClose()
}
const tempId = ref('')
function renameFile(id, dropRef) {
  centerDialogVisible.value = true
  titleInput.value = files.value[id].name
  tempId.value = id
  dropRef.handleClose()
}
function deleteFile(id, dropRef) {
  if (files.value.hasOwnProperty(id)) {
    delete files.value[id];
    localStorage.setItem('docs', JSON.stringify(files.value))
  }
  dropRef.handleClose()
}
function renameConfirm(){
  files.value[tempId.value].name = titleInput.value
  localStorage.setItem('docs', JSON.stringify(files.value))
  centerDialogVisible.value = false
  ElMessage({
    message: '修改成功',
    type: 'success',
  })
}
</script>

<style lang="scss" scoped>
.dialog{
  .header{
    color: black;
    padding: 10px 0;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1.5em;
    font-weight: 900;
    position: relative;
    box-sizing: border-box;
    border-bottom: 1px solid #dedede;
    .x{
      position: absolute;
      right: 0;
      margin-right: 15px;
      font-weight: normal;
      cursor: pointer;
    }
  }
  .content{
    .table-header{
      display: flex;
      justify-content: space-between;
      height: 2em;
      align-items: center;
      color: black;
      font-size: 1.1em;
      font-weight: 700;
      .name{
        flex: 1 1 50%;
        padding: 0 0 0 10px;
      }
      .save-time{
        flex: 1 1 50%;
        padding: 0 0 0 10px;
      }
    }
    .table-row{
      display: flex;
      position: relative;
      justify-content: space-between;
      height: 2em;
      align-items: center;
      color: black;
      transition: 0.2s linear;
      &:hover{
        background: #f6f6f6;
      }
      .name{
        height: 100%;
        display: flex;
        align-items: center;
        flex: 1 1 50%;
        padding: 0 0 0 10px;
        cursor: pointer;
        overflow: hidden;
        .text{
          white-space:nowrap;
          text-overflow:ellipsis;
          overflow:hidden;
        }
        .icon-24gl-fileText{
          color: #454545;
          font-size: 1em;
          margin-right: 0.5em;
        }
      }
      .save-time{
        flex: 1 1 50%;
        padding: 0 0 0 10px;
      }
      .more-option{
        position: absolute;
        right: 0;
        margin: 0 20px 0 0;
        cursor: pointer;
        display: flex;
        .icon-gengduo{
          color: #454545;
          font-size: 1em;
        }
      }
    }
    .pagination{
      justify-content: center;
      padding: 10px 0;
    }
    .buttons{
      display: flex;
      justify-content: space-between;
      padding: 0 20px 20px;
      .button{
        padding: 3px 15px;
        border: 1px solid #dcdfe6;
        border-radius: 5px;
        cursor: pointer;
      }
      .confirm{
        background: #409eff;
        color: white;
        border-color: #409eff;
      }
    }
  }
}
.dropdown{
  padding: 8px;
  .row{
    display: flex;
    padding: 5px;
    cursor: pointer;
    transition: 0.2s linear;
    border-radius: 3px;
    &:hover{
      background: #f6f6f6;
    }
    &.delete{
      .iconfont{
        color: #f55255;
      }
      color: #f55255;
    }
    .iconfont{
      color: #454545;
      margin-right: 0.5em;
    }
  }
}
</style>
